package com.cqcetbbs.smartlab.cqcetbbs.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.cqcetbbs.smartlab.cqcetbbs.R;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import jp.wasabeef.richeditor.RichEditor;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by user on 2017/10/9.
 */

public class PublishArtActivity extends Activity {

    private static final int ALBUM_OK = 1;

    //增加文章的url
    private static final String  ART_ADD = "http://api.cqcetlab.com/Home/article/add";
    private static final String TAG = PublishArtActivity.class.getSimpleName() ;
    private RichEditor mEditor;
    private TextView mPreview;
    private TextView tv_cancal;
    private TextView tv_publish;
    private boolean isOne = true;
    private  EditText et_title;
    private  String linkname;
    String[] link ;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish);
        initView();
    }

    private void initView() {
        mEditor = findViewById(R.id.editor);
        mEditor.setEditorHeight(200);
        mEditor.setEditorFontSize(22);
        mEditor.setEditorFontColor(Color.BLACK);
        mEditor.setPadding(10, 10, 10, 10);
        mEditor.setPlaceholder("Insert text here...");
        mPreview = findViewById(R.id.preview);
        tv_cancal = findViewById(R.id.tv_cancal);
        tv_publish = findViewById(R.id.tv_publish);
        et_title = findViewById(R.id.et_title);

        tv_cancal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        tv_publish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isOne) {
                 String   title =  et_title.getText().toString().trim();
                    if(TextUtils.isEmpty(title)){
                        Toast.makeText(PublishArtActivity.this,"文章标题不能为空",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    mPreview.setText( mPreview.getText() );
                    Log.e("mPreview", mPreview.getText().toString());
                    uploadArt(title,mPreview.getText().toString());
                } else {

                }

            }
        });


        mPreview = findViewById(R.id.preview);
        mEditor.setOnTextChangeListener(new RichEditor.OnTextChangeListener() {
            @Override
            public void onTextChange(String text) {
                mPreview.setText(text);
            }
        });


        findViewById(R.id.action_undo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.undo();
            }
        });

        findViewById(R.id.action_redo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.redo();
            }
        });

        findViewById(R.id.action_bold).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setBold();
            }
        });

        findViewById(R.id.action_italic).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setItalic();
            }
        });

        findViewById(R.id.action_subscript).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setSubscript();
            }
        });

        findViewById(R.id.action_superscript).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setSuperscript();
            }
        });

        findViewById(R.id.action_strikethrough).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setStrikeThrough();
            }
        });

        findViewById(R.id.action_underline).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setUnderline();
            }
        });

        findViewById(R.id.action_heading1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setHeading(1);
            }
        });

        findViewById(R.id.action_heading2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setHeading(2);
            }
        });

        findViewById(R.id.action_heading3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setHeading(3);
            }
        });

        findViewById(R.id.action_heading4).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setHeading(4);
            }
        });

        findViewById(R.id.action_heading5).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setHeading(5);
            }
        });

        findViewById(R.id.action_heading6).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setHeading(6);
            }
        });

        findViewById(R.id.action_txt_color).setOnClickListener(new View.OnClickListener() {
            private boolean isChanged;

            @Override
            public void onClick(View v) {
//                mEditor.setTextColor(isChanged ? Color.BLACK : Color.RED);
//                isChanged = !isChanged;
//                mEditor.setTextColor(1);
                SetColor();
            }
        });

        findViewById(R.id.action_bg_color).setOnClickListener(new View.OnClickListener() {
            private boolean isChanged;

            @Override
            public void onClick(View v) {
//                mEditor.setTextBackgroundColor(isChanged ? Color.WHITE : Color.YELLOW);
//                isChanged = !isChanged;
                SetbgColor();

            }
        });

        findViewById(R.id.action_indent).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setIndent();
            }
        });

        findViewById(R.id.action_outdent).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setOutdent();
            }
        });

        findViewById(R.id.action_align_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setAlignLeft();
            }
        });

        findViewById(R.id.action_align_center).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setAlignCenter();
            }
        });

        findViewById(R.id.action_align_right).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setAlignRight();
            }
        });

        findViewById(R.id.action_blockquote).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setBlockquote();
            }
        });

        findViewById(R.id.action_insert_bullets).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setBullets();
            }
        });

        findViewById(R.id.action_insert_numbers).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.setNumbers();
            }
        });

        findViewById(R.id.action_insert_image).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                跳转到相册
                Intent albumIntent = new Intent(Intent.ACTION_PICK, null);
                albumIntent.setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(albumIntent, ALBUM_OK);

//               Intent intent =  new Intent(PublishArtActivity.this,CropActivity.class);
//                startActivity(intent);


//                mEditor.insertImage("http://www.1honeywan.com/dachshund/image/7.21/7.21_3_thumb.JPG",
//                        "dachshund");
            }
        });

        findViewById(R.id.action_insert_link).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mEditor.insertLink("https://github.com/wasabeef", "wasabeef");

                //显示输入链接对话框
//                String[] strings = showDialog();
                AlertDialog.Builder dialog = new AlertDialog.Builder(PublishArtActivity.this);
                View view = View.inflate(PublishArtActivity.this,R.layout.add_link_dialog_layout,null);
                dialog.setView(view);
                final EditText et_link = view.findViewById(R.id.et_link);
                final  EditText et_linkname = view.findViewById(R.id.et_linkname);

                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int i) {

                        mEditor.insertLink(et_link.getText().toString(),et_linkname.getText().toString());
                    }
                });
                dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int i) {
                        dialog.dismiss();
                    }
                });
                dialog.show();


            }
        });

        findViewById(R.id.action_insert_checkbox).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditor.insertTodo();
            }
        });


    }

    //将文章上传到服务器,文章标题作为文件名
    private void uploadArt(String title,String content) {

        //将文章内容读取到文件中
        writeTxtToFile(content,title);

        Log.e("getFilesDir()",getFilesDir().toString());
        File  art_file = new File(getFilesDir(), title+".html");
//
//        if(!art_file.exists()){
//            try {
//                art_file.createNewFile();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }


        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), art_file);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("title",title)
                .addFormDataPart("desc","")
                .addFormDataPart("pic","")
                .addFormDataPart("content", "art_file", fileBody)
                .build();
        final Request request = new Request.Builder()
                .url(ART_ADD)
                .post(requestBody)
                .build();


        final okhttp3.OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
        OkHttpClient okHttpClient  = httpBuilder
                //设置超时
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "uploadMultiFile() e=" + e);
                Toast.makeText(PublishArtActivity.this,"发布失败！",Toast.LENGTH_SHORT).show();
            }


            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e(TAG, "uploadMultiFile() response=" + response.code());
                Toast.makeText(PublishArtActivity.this,"发布成功！",Toast.LENGTH_SHORT).show();
            }
        });

    }

    private int current, conserve=2;
    private void SetColor() {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("设置字体颜色");

        String items[] = { "红色", "黄色", "绿色", "橙色", "蓝色" ,"紫色","黑色","白色"};
        builder.setSingleChoiceItems(items, conserve, new AlertDialog.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                current = which;// 得到选中的条目
            }
        });

        builder.setPositiveButton("确定", new AlertDialog.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                System.out.println(which + "..............................");
//                WebSettings settings = wedview.getSettings();
                switch (current) {
                    case 0:
                        mEditor.setTextColor(Color.RED);
//                        settings.setTextSize(TextSize.LARGEST);
                        break;
                    case 1:
                        mEditor.setTextColor(Color.YELLOW);
//                        settings.setTextSize(TextSize.LARGER);
                        break;
                    case 2:
                        mEditor.setTextColor(Color.GREEN);
//                        settings.setTextSize(TextSize.NORMAL);
                        break;
                    case 3:
                        mEditor.setTextColor(Color.rgb(22,107 ,201));
//                        settings.setTextSize(TextSize.SMALLER);
                        break;
                    case 4:
                        mEditor.setTextColor(Color.BLUE);
//                        settings.setTextSize(TextSize.SMALLEST);
                        break;
                    case 5:
                        mEditor.setTextColor(Color.rgb(255,0 ,255));
//                        settings.setTextSize(TextSize.SMALLEST);
                        break;
                    case 6:
                        mEditor.setTextColor(Color.BLACK);
//                        settings.setTextSize(TextSize.SMALLEST);
                        break;
                    case 7:
                        mEditor.setTextColor(Color.WHITE);
//                        settings.setTextSize(TextSize.SMALLEST);
                        break;

                    default:
                        break;
                }
                conserve = current;

            }
        });

        builder.setNegativeButton("取消", null);
        builder.show();

    }


    private void SetbgColor() {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("设置背景颜色");

        String items[] = { "红色", "黄色", "绿色", "橙色", "蓝色" ,"紫色","黑色","白色"};
        builder.setSingleChoiceItems(items, conserve, new AlertDialog.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                current = which;// 得到选中的条目
            }
        });

        builder.setPositiveButton("确定", new AlertDialog.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                System.out.println(which + "..............................");
//                WebSettings settings = wedview.getSettings();
                switch (current) {
                    case 0:
                       mEditor.setTextBackgroundColor(Color.RED);
//                        settings.setTextSize(TextSize.LARGEST);
                        break;
                    case 1:
                        mEditor.setTextBackgroundColor(Color.YELLOW);
//                        settings.setTextSize(TextSize.LARGER);
                        break;
                    case 2:
                        mEditor.setTextBackgroundColor(Color.GREEN);
//                        settings.setTextSize(TextSize.NORMAL);
                        break;
                    case 3:
                        mEditor.setTextBackgroundColor(Color.rgb(22,107 ,201));
//                        settings.setTextSize(TextSize.SMALLER);
                        break;
                    case 4:
                        mEditor.setTextBackgroundColor(Color.BLUE);
//                        settings.setTextSize(TextSize.SMALLEST);
                        break;
                    case 5:
                        mEditor.setTextBackgroundColor(Color.rgb(255,0 ,255));
//                        settings.setTextSize(TextSize.SMALLEST);
                        break;
                    case 6:
                        mEditor.setTextBackgroundColor(Color.BLACK);
//                        settings.setTextSize(TextSize.SMALLEST);
                        break;
                    case 7:
                        mEditor.setTextBackgroundColor(Color.WHITE);
//                        settings.setTextSize(TextSize.SMALLEST);
                        break;

                    default:
                        break;
                }
                conserve = current;

            }
        });

        builder.setNegativeButton("取消", null);
        builder.show();

    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (ALBUM_OK == requestCode) {
//            Toast.makeText(this, "OK now", Toast.LENGTH_SHORT).show();
            Bitmap bitmap;
            Log.e("MainActivity ", " onActivityResult ");
            ContentResolver cr = this.getContentResolver();
            if (data == null) {
                //没有选择图片
                return;
            }
            Uri uri = data.getData();
            Log.e("uri==================", uri.toString());

            mEditor.insertImage(uri + "",
                    "图片，加载异常");
            try {
                bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
                Log.e("MainActivity ", " onActivityResult "
                        + data.getData().toString());//此处用Log.e，仅是为了查看红色Log方便
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    private String getImagePath(Uri uri) {
        if (null == uri) {
            Log.e("getImagePath", "uri return null");
            return null;
        }

        Log.e("getImagePath", uri.toString());
        String path = null;
        final String scheme = uri.getScheme();
        if (null == scheme) {
            path = uri.getPath();
        } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            path = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(uri, proj, null, null,
                    null);
            int nPhotoColumn = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            if (null != cursor) {
                cursor.moveToFirst();
                path = cursor.getString(nPhotoColumn);
            }
            cursor.close();
        }

        return path;
    }

    public static boolean isNullOrEmpty(Object obj) {
        if (obj == null)
            return true;

        if (obj instanceof CharSequence)
            return ((CharSequence) obj).length() == 0;

        if (obj instanceof Collection)
            return ((Collection) obj).isEmpty();

        if (obj instanceof Map)
            return ((Map) obj).isEmpty();

        if (obj instanceof Object[]) {
            Object[] object = (Object[]) obj;
            if (object.length == 0) {
                return true;
            }
            boolean empty = true;
            for (int i = 0; i < object.length; i++) {
                if (!isNullOrEmpty(object[i])) {
                    empty = false;
                    break;
                }
            }
            return empty;
        }
        return false;
    }


    // 将字符串写入到文本文件中
    public void writeTxtToFile(String strcontent, String fileName) {

        String strContent = strcontent;
        try {
            File file = new File(getFilesDir(),fileName+".html");

//            if (!file.exists()) {
//                Log.d("TestFile", "Create the file:" + file);
//                file.getParentFile().mkdirs();
//                file.createNewFile();
//            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            Log.e("TestFile", "Error on write File:" + e);
        }
    }


}
